﻿using System;
using System.Text;
using ElectronicCommerce.Framework.ExceptionManagement.ExHandler;
using ElectronicCommerce.Framework.ExceptionManagement.Interface;
using ElectronicCommerce.Framework.Logging;

namespace ElectronicCommerce.Framework.ExceptionManagement.LogHandler
{
    /// <summary>
    /// 框架提供的默认日志记录器类, 范例
    /// </summary>
    public class DefaultLogHandler : IExLogHandler
    {
        /// <summary>
        /// 进行截取过滤以获取错误代码行
        /// </summary>
        /// <param name="e">系统异常</param>
        /// <returns>代码行位置信息</returns>
        private string GetExceptionLocation(System.Exception e)
        {
            string strErr, sLocate = "";

            //获取源异常信息
            strErr = e.StackTrace;

            if (strErr != string.Empty && strErr != null)
            {
                if (strErr.IndexOf("\r\n") == -1)
                {
                    sLocate = strErr;
                }
                else
                {
                    if (strErr.IndexOf("\r\n") > 0)
                    {
                        sLocate = strErr.Substring(strErr.LastIndexOf("\r\n"));
                    }
                }
            }

            return sLocate.Trim();
        }


        /// <summary>
        /// 异常日志记录方法
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="strErrorCode">异常代码，在我的项目中该字段被移用为友好提示信息了</param>
        /// <param name="strLayerName">层名称</param>
        /// <param name="strUserId">当前用户Id</param>
        /// <param name="strExtention">扩展字段</param>
        /// <returns></returns>
        public void ExLog(Exception ex, string strErrorCode, string strErrorMessage, string pageAlias, string strLayerName, string strUserId, params string[] strExtention)
        {

            string ExcMsg = BuildExceptionMessage(ex, strErrorCode, strErrorMessage, pageAlias, strLayerName);

            try
            {
                Logger.Log<CommEx>(ExcMsg);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// Builds the exception message.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <returns></returns>
        private static string BuildExceptionMessage(Exception ex, string strErrorCode, string strErrorMessage, string pageAlias, string strLayerName)
        {
            StringBuilder exceptionMsgs = new StringBuilder();
            while (null != ex) // this is obsolete since we're grabbing base...
            {
                exceptionMsgs.AppendFormat("\n{0}\n{1}\n{2}\n{3}\n{4}", pageAlias, strErrorCode, strErrorMessage, ex.GetType().Name, ex.ToString());
                ex = ex.InnerException;
            }
            return exceptionMsgs.ToString();
        }
    }
}
